package com.pay;

import com.alibaba.fastjson.JSONObject;
import com.pay.bean.GlobalData;
import com.pay.bean.PayResultBean;
import com.pay.util.MD5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import static com.pay.bean.GlobalData.TEST_DATA;

@WebServlet(name = "NoteUrlServlet", urlPatterns = "/servlet/NoteUrlServlet")
public class NoteUrlServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("NoteUrlServlet post!!!");
        //获取Json请求的数据流
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer buffer = new StringBuffer();
        String temp;
        while ((temp = reader.readLine()) != null) {
            buffer.append(temp);
        }
        reader.close();
        String input = TEST_DATA;
        PayResultBean payResultBean = JSONObject.parseObject(input, PayResultBean.class);
        if (null != payResultBean) {
            System.out.println("NoteUrlServlet  payResultBean != null");
            String md5 = MD5.getMD5(GlobalData.composePayResultJsonStr(payResultBean));
            if (payResultBean.getSgn().equals(md5)) {
                if (GlobalData.STATE_SUCCESS.equals(payResultBean.getState())) {
                    System.out.println(GlobalData.STATE_SUCCESS);
                    resp.getWriter().write(GlobalData.STATE_SUCCESS);
                } else {
                    resp.getWriter().write(GlobalData.STATE_SIGN_NOT_PASSED);
                }
                return;
            }
        }
        resp.getWriter().write(GlobalData.STATE_FAILED);
        System.out.println(GlobalData.STATE_FAILED);
        return;
    }
}
